<!--
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-21 17:13:52
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-03-30 16:54:37
 * @Description:
 *
-->

<template>
  <MyContainer class="container">
    <MyHeader class="header">
      <el-input
        v-model="searchKey"
        style="width: 200px; margin-right: 20px"
        size="medium"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="medium"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-button size="medium" @click="resetClick">重置</el-button>
      <el-button
        size="medium"
        style="margin-left: auto"
        type="primary"
        icon="el-icon-plus"
        @click="allocateClick"
      >分配浮动IP</el-button>
      <el-button
        size="medium"
        type="primary"
        icon="el-icon-brush"
        :loading="btnLoadingBatchDelete"
        plain
        @click="batchDeleteClick"
      >批量释放</el-button>
      <el-button
        size="medium"
        type="primary"
        icon="el-icon-unlock"
        :loading="btnLoadingBatchDisassociate"
        plain
        @click="batchDisassociateClick"
      >批量解绑</el-button>
    </MyHeader>
    <MyMain class="main">
      <el-table
        v-loading="loading"
        class="common-table"
        :data="list"
        stripe
        header-cell-class-name="listHeaderCell"
        :header-cell-style="{ color: '#696969' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选框 -->
        <el-table-column type="selection" width="60" />
        <el-table-column
          prop="ip"
          label="IP地址"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="cloudPlatform"
          label="云服务商"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="cloudAccountName"
          label="云账号名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="externalNetwork"
          label="外部网络"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="mappedIp"
          label="已映射固定IP地址"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="mappedVm"
          label="已映射主机"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="status"
          label="状态"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="desc"
          label="描述"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createBy"
          label="创建人"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column prop="createDate" label="创建时间" width="170" />
        <el-table-column label="操作" width="210">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; padding: 0 10px"
              @click="editClick(scope.row)"
            >编辑</el-button>
            <el-popover
              :ref="`popover-delete-${scope.$index}`"
              placement="top"
              width="300"
              style="margin: 0 10px"
            >
              <p>是否确认释放该浮动IP？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    scope._self.$refs[
                      `popover-delete-${scope.$index}`
                    ].doClose()
                  "
                >取消</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="deleteClick(scope)"
                >确定</el-button>
              </div>
              <el-button
                slot="reference"
                type="danger"
                style="height: 22px; padding: 0 10px"
                size="mini"
              >释放</el-button>
            </el-popover>
            <el-button
              v-if="!scope.row.mappedVm"
              type="primary"
              size="mini"
              style="height: 22px; padding: 0 10px"
              @click="associateClick(scope.row)"
            >绑定</el-button>
            <el-popover
              v-else
              :ref="`popover-disassociate-${scope.$index}`"
              placement="top"
              width="300"
            >
              <p>是否确认解绑该浮动IP？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    scope._self.$refs[
                      `popover-disassociate-${scope.$index}`
                    ].doClose()
                  "
                >取消</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="disassociateClick(scope)"
                >确定</el-button>
              </div>
              <el-button
                slot="reference"
                type="primary"
                style="height: 22px; padding: 0 10px"
                :loading="scope.row.disassociateBtnLoading"
                size="mini"
              >解绑</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 30px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 15, 20]"
          :page-size="pageSize"
          :current-page.sync="pageNum"
          :total="totalCount"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
    </MyMain>

    <!-- 分配 -->
    <AllocateDialog
      v-if="showAllocateDialog"
      :show.sync="showAllocateDialog"
      @success="allocateSuccessCallback"
    />

    <!-- 绑定 -->
    <AssociateDialog
      v-if="showAssociateDialog"
      :show.sync="showAssociateDialog"
      :info.sync="associateInfo"
      @success="associateSuccessCallback"
    />

    <!-- 编辑 -->
    <el-dialog
      v-if="showUpdateDialog"
      class="allocate-dialog"
      title="编辑浮动IP"
      :visible="showUpdateDialog"
      width="35vw"
      top="15vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="showUpdateDialog = false"
    >
      <el-form
        ref="formUpdate"
        :rules="rulesUpdate"
        :model="formUpdate"
        label-width="auto"
      >
        <el-form-item label="IP地址" prop="ip">
          <el-input
            v-model="formUpdate.ip"
            placeholder="请输入云服务商"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="formUpdate.desc"
            placeholder="请输入描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="showUpdateDialog = false"
        >取 消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="dialogUpdateConfirmLoading"
          @click="dialogUpdateConfirmClick"
        >确 定</el-button>
      </div>
    </el-dialog>
  </MyContainer>
</template>

<script>
import pagePermissionMixin from '@/views/mixin/pagePermission.js'
import pageQueryMixin from '@/views/mixin/pageQuery.js'
import MyContainer from '@/components/Layout/MyContainer.vue'
import MyHeader from '@/components/Layout/MyHeader.vue'
import MyMain from '@/components/Layout/MyMain.vue'
import {
  getFloatIPList,
  deleteFloatIP,
  disassociateFloatIP,
  updateFloatIP
} from '@/api/cn-resource'
import AllocateDialog from './AllocateDialog.vue'
import AssociateDialog from './AssociateDialog.vue'

export default {
  name: 'FloatIP',
  components: {
    MyContainer,
    MyHeader,
    MyMain,
    AssociateDialog,
    AllocateDialog
  },
  mixins: [pagePermissionMixin, pageQueryMixin],
  data() {
    return {
      selection: [],
      btnLoadingBatchDelete: false, // 批量释放loading
      btnLoadingBatchDisassociate: false, // 批量解绑loading
      showAllocateDialog: false, // 分配dialog
      showAssociateDialog: false, // 绑定dialog
      associateInfo: {}, // 绑定基本信息
      showUpdateDialog: false, // 更新dialog
      formUpdate: {
        id: '',
        ip: '',
        desc: ''
      },
      rulesUpdate: {},
      dialogUpdateConfirmLoading: false
    }
  },
  created() {},
  methods: {
    /**
     * @description: 分配浮动IP
     * @return {*}
     */
    allocateClick() {
      this.showAllocateDialog = true
    },
    /**
     * @description: 分配成功
     * @return {*}
     */
    allocateSuccessCallback() {
      this.pageNum = 1
      this.getList() // 请求数据
    },
    /**
     * @description: 编辑
     * @return {*}
     */
    editClick(row) {
      this.formUpdate = {
        id: row.id,
        ip: row.ip,
        desc: row.desc
      }
      this.showUpdateDialog = true
    },
    /**
     * @description: 编辑 确定
     * @return {*}
     */
    dialogUpdateConfirmClick() {
      // 校验
      this.$refs.formUpdate.validate((valid, obj) => {
        if (valid) {
          // 合法
          this.dialogUpdateConfirmLoading = true
          updateFloatIP({
            ...this.formUpdate
          })
            .then((res) => {
              this.$message.success({
                message: '编辑浮动IP成功！',
                duration: '2000'
              })
              this.showUpdateDialog = false // 取消弹窗
              this.getList() // 刷新数据
            })
            .finally(() => {
              this.dialogUpdateConfirmLoading = false
            })
        }
      })
    },
    /**
     * @description: 绑定成功
     * @return {*}
     */
    associateSuccessCallback() {
      this.$message.success({
        message: '绑定浮动IP成功！',
        duration: '2000'
      })
      this.getList() // 刷新数据
    },
    /**
     * @description: 绑定
     * @return {*}
     */
    associateClick(row) {
      this.associateInfo = {
        id: row.id,
        ip: row.ip,
        cloudPlatform: row.cloudPlatform,
        cloudAccountName: row.cloudAccountName,
        portId: ''
      }
      this.showAssociateDialog = true
    },
    /**
     * @description: 解绑
     * @param {*} row
     * @param {*} index
     * @return {*}
     */
    disassociateClick(scope) {
      scope._self.$refs[`popover-disassociate-${scope.$index}`].doClose() // 取消popover
      this.$set(this.list[scope.$index], 'disassociateBtnLoading', true)
      const row = scope.row
      disassociateFloatIP({
        ids: [row.id]
      })
        .then((res) => {
          this.$message.success('解绑成功')
          this.getList() // 请求数据
        })
        .finally(() => {
          this.list[scope.$index].disassociateBtnLoading = false
        })
    },
    /**
     * @description: 批量解绑
     * @return {*}
     */
    batchDisassociateClick() {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择浮动IP')
        return
      }
      const ids = []
      for (const item of this.selection) {
        ids.push(item.id)
      }
      this.$confirm('是否确认批量解绑当前已选中的浮动IP？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        this.btnLoadingBatchDisassociate = true
        disassociateFloatIP({ ids })
          .then((res) => {
            this.selection = []
            this.$message.success('批量解绑成功')
            this.getList() // 请求数据
          })
          .finally(() => {
            this.btnLoadingBatchDisassociate = false
          })
      })
    },
    /**
     * @description: 释放
     * @param {*} row
     * @param {*} index
     * @return {*}
     */
    deleteClick(scope) {
      const row = scope.row
      deleteFloatIP({
        ids: [row.id]
      }).then((res) => {
        scope._self.$refs[`popover-delete-${scope.$index}`].doClose() // 取消popover
        this.$message.success('释放成功')
        if (this.list.length === 1) {
          // 当前页只有一条数据时 删除完刷新上一页数据
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getList() // 请求数据
      })
    },
    /**
     * @description: 批量释放
     * @return {*}
     */
    batchDeleteClick() {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择浮动IP')
        return
      }
      const ids = []
      for (const item of this.selection) {
        ids.push(item.id)
      }
      this.$confirm('是否确认批量释放当前已选中的浮动IP？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        this.btnLoadingBatchDelete = true
        deleteFloatIP({ ids })
          .then((res) => {
            this.selection = []
            this.$message.success('批量释放成功')
            if (this.list.length === 1) {
              // 当前页只有一条数据时 删除完刷新上一页数据
              this.pageNum = Math.max(this.pageNum - 1, 1)
            }
            this.getList() // 请求数据
          })
          .finally(() => {
            this.btnLoadingBatchDelete = false
          })
      })
    },
    /**
     * @description: 选择
     * @param {*} selection
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.selection = selection
    },
    /**
     * @description: 获取列表
     * @return {*}
     */
    getList() {
      this.handleRequestAndResp(getFloatIPList, {
        keyword: this.searchKey,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.container {
}
</style>
